import React from "react";
import {BaseEventOrig, Image, View} from "@tarojs/components";
import {ImageProps} from "@tarojs/components/types/Image";
import Taro from "@tarojs/taro"

import styles from "./MessageImageCell.module.scss";
import {Async} from "../../Async";
import {getSystemInfo} from "../../wxapi";

interface Props {
  origin: {url:string}
}

interface State {
  style:string;
}

export class MessageImageCell extends React.Component<Props, State> {
  constructor(args: Props | Readonly<Props>) {
    super(args);

    this.state = {
      style:"display:none"
    }
  }
  componentWillMount () {
  }

  componentDidMount () {
    Async(async ()=> {
      let ret = await Taro.getImageInfo({src:this.props.origin.url});
      await this.updateStyle(ret.width, ret.height);
    })
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }


  async updateStyle(width:number, height:number):Promise<void> {
    const [ret, _] = await getSystemInfo();
    const maxSize = ret?.windowWidth!-100;

    let style = `width:${width}px; height:${height}px;`;
    if (width>height && width>maxSize) {
      let scaleHeight = height*maxSize/width;
      style = `width: ${maxSize}px; height: ${scaleHeight}px`;

    } else if (height>width && height>maxSize) {
      let scaleWidth = width*maxSize/height;
      style = `width: ${scaleWidth}px; height: ${maxSize}px;`
    }
    this.setState({style:style});
  }
  imageOnLoad(e:BaseEventOrig<ImageProps.onLoadEventDetail>):void {
    Async(async ()=> {
      await this.updateStyle(Number(e.detail.width), Number(e.detail.height));
    });

  }

  render () {
    return (
      <View className={styles.container}>
        <Image src={this.props.origin.url}  mode='aspectFit'
          style={this.state.style}
          lazyLoad
          onLoad={this.imageOnLoad.bind(this)}
        />
      </View>
    )
  }
}
